package com.yilin.platform.base_core.application;

import com.google.gson.reflect.TypeToken;
import com.yilin.platform.base_core.commons.encrypt.EncryptUtils;
import com.yilin.platform.base_core.commons.utils.HttpService;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.MapUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import org.springframework.context.ApplicationContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

public class AppUtil {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    //判断是否为数字
    public static boolean isNumeric(String str) {
        if (str == null) return false;
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String md5(String str) {
        StringBuilder sb = new StringBuilder(32);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(str.getBytes(StandardCharsets.UTF_8));
            for (byte b : array) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).toUpperCase(), 1, 3);
            }
        } catch (Exception e) {
            return "";
        }
        return sb.toString();
    }

    /*
     * 生成随机数 int number---生成随机数个数
     */
    public static String random(int number) {
        Random random = new Random();
        StringBuilder random5 = new StringBuilder();
        for (int i = 0; i < number; i++) {
            random5.append(random.nextInt(10));
        }
        return random5.toString();
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return Character.toLowerCase(s.charAt(0)) + s.substring(1);
        }
    }

    //获取临时上传地址
    public static String getUpLoadPath(HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("/upload/");
        if (!new File(realPath).exists()) new File(realPath).mkdirs();
        return realPath;
    }

    public static String getTemporaryPath(String path) {
        File file = new File(path);
        if (!file.exists())file.mkdirs();
        return file.getPath();
    }

    private final static String baseUrl = "http://127.0.0.1:30002";
    public static List<Map<String,Object>> migrationListPost(String path, Map<String,Object> param){
        String jsonStr = migrationPost( path,  param);
        if (jsonStr==null) return new ArrayList<>();
        return JsonUtil.jsonToObject(jsonStr,new TypeToken<List<Map<String, Object>>>(){});
    }

    public static String migrationPost(String path, Map<String,Object> param){
        String json = JsonUtil.objectToJson(param);
        String aesEncrypt = EncryptUtils.aesEncrypt(json, null);
        Map<String,Object> body = new HashMap<>();
        body.put("body",aesEncrypt);
        String data = HttpService.httpPostWithJson(String.format("%s%s",baseUrl,path), JsonUtil.objectToJson(body), MapUtil.generate(map -> map.put("migration","migration4_0_to_4_5")));
        if(StringUtil.isEmpty(data)) return null;
        Map<String, Object> map = JsonUtil.jsonToObject(data, new TypeToken<Map<String, Object>>() {});
        return EncryptUtils.aesDecrypt((String) map.get("data"), null);
    }

}
